package cn.zyx.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component // 交给容器扫描
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException{
        // 判断用户是否登录了
        // 获取前端储存的token
        String token = request.getHeader("token");
        // 判断前端储存的token是否为空
        if(!StringUtils.isEmpty(token)){
            // 获取后端存储的token
            Object obj = redisTemplate.opsForValue().get(token);
            // 不为空表示已经登录过了
            if (obj != null){
                // 刷新redis中的token的存储时间
                redisTemplate.opsForValue().set(token, obj, 30, TimeUnit.MINUTES);
                // 放行
                return true;
            }
        }
        // 为空表示没有登录
        response.setContentType("application/json;charset=UTF-8"); // restFul风格设置编码
        PrintWriter writer = response.getWriter();  // 往请求体中写数据
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush(); // 刷新
        writer.close(); // 关流
        return false;
    }
}
